package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        //jdbc查询数据库操作
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
        String user = "root";
        String password = "173565";
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection(url, user, password);

            //3.sql语句
            String sql = "select * from sys_user";

            PreparedStatement ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            //7.判断是否成功
            while (rs.next()) {
                User u=new User();
                u.setId(rs.getInt(1));
                u.setName(rs.getString(2));
                u.setPass(rs.getString(3));
                users.add(u);
            }
            return users;
            //8.返回视图
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (conn != null) {
                    conn.close();
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
